<script setup>
import router from "@/router/index.js";
import {reactive} from "vue";
import {ElMessage} from "element-plus";
import request from "@/utils/request.js";

const data = reactive({
  user: JSON.parse(localStorage.getItem('code_user'))
})

const handleFileSuccess = (res) => {
  if (res.code === '200'){
    data.user.avatar = res.data
    ElMessage.success("上传成功")
  }else {
    ElMessage.error(res.msg)
  }
}

const handleExceed = (files, fileList) => {
  ElMessage.warning("只能上传一张头像");
};


const emit = defineEmits(['updateUser'])

const save = () => {
  request.put('/user/update',data.user).then(res => {
    if (res.code === '200'){
      ElMessage.success('更新成功')
      localStorage.setItem("code_user", JSON.stringify(data.user))
      emit('updateUser')
    }else {
      ElMessage.error(res.msg)
    }
  })
}

</script>

<template>
  <div>
<!--    返回-->
    <div style="display: flex;align-items: center;flex-direction: row;margin-top: 10px"
         @click="router.push('/home')">
      <el-icon size="large"><Back /></el-icon>
      <span style="margin-left: 5px">返回</span>
    </div>

    <div class="card" style="width: 100%;margin-top: 20px">
      <div style="font-size: 15px;">个人信息</div>
      <el-form ref="formRef" :model="data.user" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="username" label="账号" >
          <el-input v-model="data.user.username" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="name" label="名称" >
          <el-input v-model="data.user.name" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="phone" label="电话" >
          <el-input v-model="data.user.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="email" label="邮箱" >
          <el-input v-model="data.user.email" autocomplete="off" />
        </el-form-item>
        <el-form-item prop="avatar" label="头像" >
          <div>
            <el-upload
                action="http://localhost:9999/files/upload"
                :headers="{ token: data.user.token }"
                :on-success="handleFileSuccess"
                list-type="picture"
                :limit="1"
                :on-exceed="handleExceed"
                class="custom-upload"
            >
              <el-button type="primary">上传头像</el-button>
            </el-upload>
          </div>
        </el-form-item>
      </el-form>

      <div style="text-align: center">
        <el-button type="primary" style="padding: 20px 35px;width: 100%" @click="save">保存</el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.custom-upload :deep(.el-upload-list__item) {
  width: 80px !important;
  height: 80px !important;
  margin: 5px;
}
.custom-upload :deep(.el-upload-list) {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-width: 300px;
  overflow: hidden;
}
</style>